<template>
  <el-dialog
    :title="title"
    :visible.sync="showDialog"
    width="50%"
    :before-close="handleClose"
  >
    <el-form ref="form" :model="formData" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="请填写部门名称"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="请填写部门编码"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getPeople"
        >
          <el-option
            v-for="item in peopleList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="请填写部门介绍"
        />
      </el-form-item>
      <el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addDepartment, getDepartmentDetail, getDepartmentList, updateDepartment } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    node: {
      type: Object,
      default: null
    }
  },
  data() {
    // 校验添加部门名称是否重复
    const checkNameRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartmentList()
      let arr = []
      if (this.formData.id) {
        // 编辑部门校验：不能与兄弟节点同名
        // 注意：这里是每一项不等于此时正在操作的节点，并不是此时的formData
        arr = depts.filter(item => item.id !== this.node.id && item.pid === this.node.pid)
      } else {
        // 编辑部门校验：不能与子节点同名
        arr = depts.filter(item => item => item.pid === this.node.id)
      }
      // 查找该部门下的子部门是否有名字重复的
      const isRepeat = arr.some(item => item.name === value)
      isRepeat ? callback(new Error(`该部门下已经存在${value}部门`)) : callback()
    }

    // 校验添加部门编码是否重复
    const checkCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartmentList()
      let isRepeat = false
      if (this.formData.id) {
        // 编辑部门编码：不能与自己相同
        isRepeat = depts.some(item => item.id !== this.node.id && item.code === value)
      } else {
        // 查找所有的部门是否有编码重复的
        isRepeat = depts.some(item => item.code === value)
      }
      isRepeat ? callback(new Error(`组织架构中已经使用过${value}编码`)) : callback()
    }
    return {
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkNameRepeat, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkCodeRepeat, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 300,
            message: '部门介绍要求1-50个字符'
          }
        ]
      },
      peopleList: []
    }
  },
  computed: {
    title() {
      if (this.formData.id) {
        return '编辑部门'
      }
      return '新增部门'
    }
  },
  methods: {
    async handleClose() {
      this.formData = {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      }
      await this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
    },
    // 点击提交按钮
    async onSubmit() {
      await this.$refs.form.validate()
      if (this.formData.id) {
        await updateDepartment(this.formData)
        this.$message.success('编辑部门成功')
      } else {
        await addDepartment({ ...this.formData, pid: this.node.id })
        this.$message.success('添加部门成功')
      }

      // 通知父组件刷新页面
      this.$emit('success')
      // 关闭弹出层
      this.handleClose()
    },
    // 获取下拉选择框的数据
    async getPeople() {
      this.peopleList = await getEmployeeSimple()
    },
    // 定义编辑数据回显函数，让父组件进行调用，因为如果在子组件使用，不好在点击编辑打开弹出框的时候调用接口
    async getDepartmentDetail(id) {
      this.formData = await getDepartmentDetail(id)
    }
  }
}
</script>

<style>
</style>
